<?php

namespace App\Models\Cart;

use App\Models\BaseModel;

/**
 * 购物车明细模型类
 *
 * @package App\Models\Goods
 */
class CartItem extends BaseModel
{
    protected $table = 'b2c_cart_item';
    protected $primaryKey = 'item_id';

    /**
     * 根据购物车 Id 获取明细
     *
     * @param int $cartId
     * @param int $isSelected
     * @return
     */
    public static function getItems(int $cartId, int $isSelected = 0)
    {
        $cartItems = CartItem::query()->where('cart_id', $cartId);
        if(!empty($isSelected)) {
            $cartItems->where('is_selected', $isSelected);
        }
        return $cartItems->get();
    }

    /**
     * 根据 Id 获取明细
     *
     * @param int $itemId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public static function getById(int $itemId)
    {
        return CartItem::query()->where('item_id', $itemId)->first();
    }

    /**
     * 根据 Id 获取明细
     *
     * @param int $cartId
     * @param int $productId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public static function getByCartIdAndProductId(int $cartId, int $productId)
    {
        return CartItem::query()->where('cart_id', $cartId)->where('product_id', $productId)->first();
    }

    /**
     * 根据购物车ID、商品ID获取购物车明细
     *
     * @param int $cartId
     * @param int $productId
     * @return
     */
    public static function checkItem(int $cartId, int $productId)
    {
        return CartItem::query()->where('cart_id', $cartId)->where('product_id', $productId)->first();
    }

    /**
     * 获取待结算的商品
     *
     * @param int $cartId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getIsSelectedItems(int $cartId)
    {
        return CartItem::query()->where('cart_id', $cartId)->where('is_selected', 1)->get();
    }

    /**
     * 删除购物车商品
     *
     * @param array $itemIds
     * @return mixed
     */
    public static function remove(array $itemIds)
    {
        return CartItem::query()->whereIn('item_id', $itemIds)->delete();
    }

    /**
     * 根据客户 Id 获取购物车明细
     *
     * @param int $customerId
     * @param int $fastBuy
     * @param int $isSelected
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getItemsByCustomerId(int $customerId, int $fastBuy = 0, int $isSelected = 0)
    {
        $cart = Carts::getByCustomerId($customerId, $fastBuy);
        $cartItems = CartItem::getItems($cart->cart_id, $isSelected);
        return $cartItems;
    }
}
